package edu.gxmzu.task.controller;

import com.alibaba.fastjson.JSONObject;
import edu.gxmzu.task.entity.*;
import edu.gxmzu.task.mapper.AttachmentsMapper;
import edu.gxmzu.task.service.TaskDisposeService;
import edu.gxmzu.task.utils.FileHashUtil;
import edu.gxmzu.task.utils.FileUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * author: lrf
 * time: 2024-11-29
 * version : V1
 */
@Tag(name = "任务模块")
@RestController
public class TaskDisposeController {
    private static final Logger logger = LoggerFactory.getLogger(TaskDisposeController.class);
    @Autowired
    private TaskDisposeService taskDisposeService;

    @Value("${server.port}")
    private String port;

    @Value("${ip:localhost}")
    private String ip;

    /**
     * author: lrf
     * time: 2024-11-29
     * version : V1
     * detail: 获取下发人员接口
     * @return
     */
    @GetMapping("/getUsername")
    @Operation(summary = "获取下发人员")
    public Map<String, Object> getUserName(@Param("name") String name){
        Map<String, Object> result = new HashMap<>();       // 返回结果集
        List<Map<String, Object>> resultName = taskDisposeService.getUserName(name);
        List<Map<String, String>> resultName1 = new ArrayList<>();

        resultName.forEach(item -> {
            Map<String, String> result1 = new HashMap<>(); // 在循环内创建新的对象
            item.forEach((key, value) -> {
                result1.put(key, value.toString());
            });
            resultName1.add(result1);
        });
        logger.info("resultName1=================》》》lrf====>>" + JSONObject.toJSON(resultName1));
        if (Objects.nonNull(resultName) && !resultName.isEmpty()) {
            result.put("code", 200);
            result.put("data", resultName1);
            result.put("status", "请求成功");
        } else {
            result.put("code", 403);
            result.put("data", resultName1);
            result.put("status", "请求失败");
        }
        return result;
    }

    /**
     * author: lrf
     * time: 2024-12-04
     * version : V2
     * detail: 任务派发
     * @return
     */
    @Operation(summary = "任务派发", description =  "{<br>" +
            "userId: 任务所属用户id (必填) 不能为空 <br>" +
            "appointorId: 指派人id（自己创建：NULL，被派发：绑定管理员id） (选填)<br>" +
            "workStatusId: 任务状态id (0：进行中，1：已完成，2：已逾期) (必填)<br>" +
            "priorityId: 任务的优先级 (0: 一般，1: 重要，2: 紧急) (必填)<br>" +
            "attachmentsId: 附件id（没有附件默认NULL） (选填)<br>" +
            "title: 标题 (必填)<br>" +
            "content: 任务的详细描述 (必填)<br>" +
            "require: 任务要求 (选填)<br>" +
            "createTime: 创建任务的时间戳 (必填)<br>" +
            "updateTime: 最后一次更新的时间戳 (必填)<br>" +
            "endTime: 任务结束的时间戳 (必填)<br>" +
            "deletionState: 逻辑删除标志 (0：未删除，1：已删除) (选填)<br>}")
    @PostMapping("/TaskAssignment")
    public Map<String, Object> taskDispose(@RequestParam(name="file",required = false) MultipartFile file, TaskDistributeEntity distribute) throws IOException {
        Map<String, Object> result = new HashMap<>();  // 返回结果集

        // 获取附件ID
        String attachmentsId = null;
        Map<String, Object> uploadResult = taskDisposeService.uploadFile(file);
        if (uploadResult != null) {
            attachmentsId = (String) uploadResult.get("id");
        }
        distribute.setAttachmentsId(attachmentsId);
        distribute.setWorkStatusId(0);
        // 执行任务下发
        int taskDistributeNum = taskDisposeService.taskDistribute(distribute);
        if (taskDistributeNum != 0) {
            result.put("code", 200);
            result.put("data", taskDistributeNum);
            result.put("status", "请求成功");
        } else {
            result.put("code", 500);
            result.put("status", "请求失败");
        }
        return result;
    }

    @Operation(summary = "管理员报表统计", description = "管理员报表统计 时间戳：createTime,endTime,title(任务名称)")
    @GetMapping("/countAdmin")
    public Map<String, Object> countTaskNum(@RequestParam(required = false) @Schema(description = "创建时间，（传时间戳）") String createTime,
                                            @RequestParam(required = false) @Schema(description = "截止时间，（传时间戳）") String endTime,
                                            @RequestParam(required = false) @Schema(description = "任务名称") String title) {
        Map<String, Object> result = new HashMap<>();

        Long startTime;
        Long endTimeValue;

        if (createTime == null || endTime == null) {
            // 默认查询最近7天的数据
            LocalDate now = LocalDate.now();
            LocalDate sevenDaysAgo = now.minusDays(8);  // 7天前（包括今天是第1天）

            // 转换为时间戳（毫秒）
            startTime = sevenDaysAgo.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            endTimeValue = now.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        } else {
            // 如果传递了时间，使用传递的参数
            startTime = Long.parseLong(createTime);
            endTimeValue = Long.parseLong(endTime);
        }

        // 获取任务统计数据
        Map<String, Integer> taskCountByDay = taskDisposeService.countTaskNum(startTime, endTimeValue, title);
        Map<String, Object> stringObjectMap = taskDisposeService.countWorkStatus(startTime, endTimeValue, title);

        // 将结果返回
        result.put("taskLineChart", taskCountByDay);
        result.put("taskHisTogram", stringObjectMap);
        return result;
    }


}
